package com.mobvel.zxstdzgl.utils;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Vector;

import android.text.TextUtils;

/**
 * 字符串服务
 * @author wenzh
 *
 */
public final class StringUtil {

	/**
	 * Splits this string around matches of the given separator
	 * 
	 * @param value
	 * @param separator
	 * @return String[]
	 */
	public static String[] splitString(String value, String separator) {
		ArrayList<String> rtn = new ArrayList<String>();
		int pos = 0;
		int pos2 = 0;
		int tagLen = separator.length();
		String temp = "";
		int i = 0;
		Vector<Integer> vpos = new Vector<Integer>();
		if (value == null || value.equals("")) {
			rtn.add("");
			return (String[]) rtn.toArray(new String[0]);
		}
		if (value.indexOf(separator) < 0) {
			rtn.add(value);
		} else {
			while (true) {
				if (i == 0) {
					pos = value.indexOf(separator, 0);
				} else {
					pos = value.indexOf(separator, tagLen + pos);
				}
				i++;
				if (pos >= 0) {
					vpos.add(Integer.valueOf(pos));
				} else {
					vpos.add(Integer.valueOf(value.length()));
					break;
				}
			}
			pos = 0;
			for (int j = 0; j < vpos.size(); j++) {
				pos2 = (vpos.get(j)).intValue();
				int te = pos2 - pos;
				if (te == 0) {
					temp = "";
				} else {
					if (j == 0) {
						temp = value.substring(pos, pos2);
					} else {
						temp = value.substring(pos + tagLen, pos2);
					}
				}
				rtn.add(temp);
				pos = pos2;
			}
		}
		return (String[]) rtn.toArray(new String[0]);
	}

	/**
	 * Splits this string around matches of the given separator
	 * 
	 * @param value
	 * @param separator
	 * @return String[]
	 */
	public static ArrayList<String> divideString(String value, String separator) {
		ArrayList<String> rtn = new ArrayList<String>();
		int pos = 0;
		int pos2 = 0;
		int tagLen = separator.length();
		String temp = "";
		int i = 0;
		Vector<Integer> vpos = new Vector<Integer>();
		if (value == null || value.equals("")) {
			rtn.add("");
			return rtn;
		}
		if (value.indexOf(separator) < 0) {
			rtn.add(value);
		} else {
			while (true) {
				if (i == 0) {
					pos = value.indexOf(separator, 0);
				} else {
					pos = value.indexOf(separator, tagLen + pos);
				}
				i++;
				if (pos >= 0) {
					vpos.add(Integer.valueOf(pos));
				} else {
					vpos.add(Integer.valueOf(value.length()));
					break;
				}
			}
			pos = 0;
			for (int j = 0; j < vpos.size(); j++) {
				pos2 = (vpos.get(j)).intValue();
				int te = pos2 - pos;
				if (te == 0) {
					temp = "";
				} else {
					if (j == 0) {
						temp = value.substring(pos, pos2);
					} else {
						temp = value.substring(pos + tagLen, pos2);
					}
				}
				rtn.add(temp);
				pos = pos2;
			}
		}
		return rtn;
	}

	/**
	 * Returns a new string resulting from replacing all occurrences of
	 * oldString in this string with newString
	 * 
	 * @param value
	 * @param tag
	 * @param replaceOf
	 * @return String
	 */
	public static String replaceString(String value, String oldString, String newString) {
		if (value == null || newString == null || oldString == null)
			return null;
		StringBuffer sbf = new StringBuffer();
		sbf.append(value);
		int len = newString.length();
		int l = oldString.length();
		int pos = 0 - len;
		String temp = "";
		if (value.equals("")) {
			return value;
		} else {
			do {
				temp = sbf.toString();
				pos = temp.indexOf(oldString, pos + len);
				if (pos >= 0) {
					sbf.replace(pos, pos + l, newString);
				}
			} while (pos >= 0);
			String aa = new String(sbf);
			return aa;
		}
	}

	/**
	 * change null to empty string
	 * 
	 * @param src
	 *            input string
	 * @return empty string
	 */
	public static String null2EmptyString(String src) {
		String s = src;
		if (TextUtils.isEmpty(src))
			s = "";
		return s.trim();
	}
	
	/**
	 * change null to null string
	 * 
	 * @param src
	 *            input string
	 * @return null string
	 */
	public static String null2NullString(String src) {
		String s = src;
		if (src == null)
			s = "null";
		return s.trim();
	}

	/** Quote metacharacters in HTML. */
	public static String HTMLCharFilter(String s) {
		if (s == null)
			return "";
		else {
			// deal with ampersands first so we can ignore the ones we add later
			int c, oldC = -1;
			String html = "";
			while ((c = s.substring(oldC + 1).indexOf('&')) != -1) {
				c += oldC + 1; // adjust back to real string start
				html = new String((new StringBuffer(s)).replace(c, c + 1, "&#38;"));
				oldC = c;
			}
			while ((c = html.indexOf('\\')) != -1)
				html = new String((new StringBuffer(html)).replace(c, c + 1, "&#92;"));
			while ((c = html.indexOf("\'")) != -1)
				html = new String((new StringBuffer(html)).replace(c, c + 1, "&#39;"));
			while ((c = html.indexOf('"')) != -1)
				html = new String((new StringBuffer(html)).replace(c, c + 1, "&#34;"));
			while ((c = html.indexOf('<')) != -1)
				html = new String((new StringBuffer(html)).replace(c, c + 1, "&#60;"));
			while ((c = html.indexOf('>')) != -1)
				html = new String((new StringBuffer(html)).replace(c, c + 1, "&#62;"));
			while ((c = html.indexOf(' ')) != -1)
				html = new String((new StringBuffer(html)).replace(c, c + 1, "&#32;"));

			return html;
		}

	}

	/**
	 * 判断字符串是否为空
	 * 
	 * @param value
	 *            字符串
	 * @return 是否为空
	 */
	public static boolean isEmpty(String value) {
		return value == null || value.trim().length() <= 0;
	}

	public static String formatStringLength(char prefix, int value, int dstLength) {
		String valueStr = String.valueOf(value);
		int length = valueStr.length();
		if (length < dstLength) {
			return StringUtil.repeatString(String.valueOf(prefix), dstLength - length) + value;
		} else if (length == dstLength) {
			return valueStr;
		} else {
			String msg = "\"value\"'s length is greater than dstLength!";
			throw new IllegalArgumentException(msg);
		}
	}

	public static String repeatString(String value, int count) {
		StringBuilder result = new StringBuilder();
		for (int i = 0; i <= count - 1; i++) {
			result.append(value);
		}

		return result.toString();
	}

	public static String toGB2312(String source) {
		String retValue = "";

		if ((source == null) || (source.trim().length() == 0))

			return retValue;

		try {
			retValue = new String(source.getBytes("iso8859-1"), "GB2312");
		} catch (UnsupportedEncodingException e) {
			return source;
		}

		return retValue;
	}

	/**
	 * 将字符串从GB2312转换为iso8859
	 * @param source String
	 * @return String
	 */
	public static String toISO8859(String source) {
		String retValue = "";
		if ((source == null) || (source.trim().length() == 0))

			return retValue;

		try {
			retValue = new String(source.getBytes("GB2312"), "iso8859-1");
		} catch (UnsupportedEncodingException e) {
			return source;

		}
		return retValue;
	}

	/**
	 * 将字符串从iso8859转换为utf8
	 * @param source String
	 * @return String
	 */
	public static String toUTF8(String source) {

		String retValue = "";

		if ((source == null) || (source.trim().length() == 0))

			return retValue;

		try {
			retValue = new String(source.getBytes("iso8859-1"), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			return source;
		}

		return retValue;
	}

	/**
	 * 返回类似139*****123的格式
	 * @param mobile
	 * @return
	 */
	public static String formatMobile(String mobile) {
		if (mobile != null && mobile.length() == 11) {
			return mobile.substring(0, 3) + "*****" + mobile.substring(8);
		} else {
			return mobile;
		}
	}

	/**
	 * 针对WNG的link “&” 转换；
	 * @param s
	 * @return
	 */
	public static String formatHtmlUrl(String s) {
		if (s == null)
			return "";
		else {
			// deal with ampersands first so we can ignore the ones we add later
			int c, oldC = -1;
			String html = "";
			while ((c = s.substring(oldC + 1).indexOf('&')) != -1) {
				c += oldC + 1; // adjust back to real string start
				html = new String((new StringBuffer(s)).replace(c, c + 1, "&amp;"));
				oldC = c;
			}

			return html;
		}

	}

	public static void main(String[] args) {
		System.out.println(buildRandom(4));
	}

	/**
	 * 取出一个指定长度大小的随机正整数.
	 * 
	 * @param length
	 *            int 设定所取出随机数的长度。length小于11
	 * @return int 返回生成的随机数。
	 */
	public static int buildRandom(int length) {
		int num = 1;
		double random = Math.random();
		if (random < 0.1) {
			random = random + 0.1;
		}
		for (int i = 0; i < length; i++) {
			num = num * 10;
		}
		return (int) ((random * num));
	}

	public static String getDateString() {
		SimpleDateFormat simpledateformat = new SimpleDateFormat ("yyyyMMdd");
	    Date dt=new Date();
	    String strDate=simpledateformat.format(dt);
	    return strDate;
	}
	
	public static String getHourString() {
		SimpleDateFormat simpledateformat = new SimpleDateFormat ("yyyyMMddhh");
	    Date dt=new Date();
	    String strDate=simpledateformat.format(dt);
	    return strDate;
	}
	

	public static String getDateStr() {
		SimpleDateFormat simpledateformat = new SimpleDateFormat ("yyyy-MM-dd");
	    Date dt=new Date();
	    return simpledateformat.format(dt);
	}
	
	public static String getTimeStr() {
		SimpleDateFormat simpledateformat = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss");
	    Date dt=new Date();
	    String strDate=simpledateformat.format(dt);
	    return strDate;
	}
	
	//类似于asp中urlencode函数的jsp函数
	public static String URLEncode(String text) {
	    StringBuffer StrUrl = new StringBuffer();
	    for (int i = 0; i < text.length(); ++i) {
	      switch (text.charAt(i)) {
	        case ' ':
	          StrUrl.append("%20");
	          break;
	        case '+':
	          StrUrl.append("%2b");
	          break;
	        case '\'':
	          StrUrl.append("%27");
	          break;
	        case '/':
	          StrUrl.append("%2F");
	          break;
	        case '.':
	          StrUrl.append("%2E");
	          break;
	        case '<':
	          StrUrl.append("%3c");
	          break;
	        case '>':
	          StrUrl.append("%3e");
	          break;
	        case '#':
	          StrUrl.append("%23");
	          break;
	        case '%':
	          StrUrl.append("%25");
	          break;
	        case '&':
	          StrUrl.append("%26");
	          break;
	        case '{':
	          StrUrl.append("%7b");
	          break;
	        case '}':
	          StrUrl.append("%7d");
	          break;
	        case '\\':
	          StrUrl.append("%5c");
	          break;
	        case '^':
	          StrUrl.append("%5e");
	          break;
	        case '~':
	          StrUrl.append("%73");
	          break;
	        case '[':
	          StrUrl.append("%5b");
	          break;
	        case ']':
	          StrUrl.append("%5d");
	          break;
	        default:
	          StrUrl.append(text.charAt(i));
	          break;
	      }
	    }
	    return StrUrl.toString();
	  }
}
